package service

import (
	"context"
	"fmt"
	"github.com/google/uuid"
	"time"
	"video-srv/basic/config"
	__ "video-srv/basic/proto/rpc"
	"video-srv/handler/model"
	"video-srv/pkg"
)

func (s *VideoServer) GetMemberList(_ context.Context, in *__.GetMemberListReq) (*__.GetMemberListResp, error) {
	var mer model.Member
	list, err := mer.GetMemberList(config.DB)
	if err != nil {
		return nil, err
	}
	return &__.GetMemberListResp{
		List: list,
	}, nil
}

func (s *VideoServer) PayMember(_ context.Context, in *__.PayMemberReq) (*__.PayMemberResp, error) {
	var user model.User
	err := user.IsUser(config.DB, int(in.UserId))
	if err != nil {
		return nil, err
	}
	var mer model.Member
	err = mer.IsMember(config.DB, int(in.MemberId))
	if err != nil {
		return nil, err
	}
	now := time.Now().Unix()
	order := model.Order{
		UserId:           int(in.UserId),
		OrderSn:          uuid.NewString(),
		Amount:           19,
		MemberExpireTime: 12345678,
		PayType:          1,
		PayTime:          int(now),
	}
	err = order.CreateOrder(config.DB)
	if err != nil {
		return nil, err
	}
	pay, err := pkg.AliPay(order.OrderSn, order.Amount)
	if err != nil {
		return nil, err
	}
	return &__.PayMemberResp{
		PayUrl: pay,
	}, nil
}

func (s *VideoServer) AliPayCallback(_ context.Context, in *__.AliPayCallbackReq) (*__.AliPayCallbackResp, error) {
	var order model.Order
	err := order.IsOrder(config.DB, in.OrderSn)
	if err != nil {
		return nil, err
	}
	switch in.TradeStatus {
	case "TRADE_SUCCESS":
		//修改订单状态
		err = order.UpdateOrderStatus(config.DB, in.OrderSn, 1)
		if err != nil {
			return nil, err
		}
		//更新过期时间
		var user model.User
		err = user.IsUser(config.DB, order.UserId)
		if err != nil {
			return nil, err
		}
		now := int(time.Now().Unix())
		if user.MemberExpireTime < now {
			user.MemberExpireTime = now + order.MemberExpireTime
		} else {
			user.MemberExpireTime += order.MemberExpireTime
		}
		err = user.UpdateUserExpireTime(config.DB, int(user.ID), user.MemberExpireTime)
		if err != nil {
			return nil, err
		}
	case "TRADE_CLOSED":
		err = order.UpdateOrderStatus(config.DB, in.OrderSn, 2)
		if err != nil {
			return nil, err
		}
	case "TRADE_FINISHED":
		if order.Status != 1 {
			return nil, fmt.Errorf("支付未完成")
		}
		err = order.UpdateOrderStatus(config.DB, in.OrderSn, 4)
		if err != nil {
			return nil, err
		}
	default:
		return nil, fmt.Errorf("待付款")
	}

	return &__.AliPayCallbackResp{}, nil
}

func (s *VideoServer) GetUserMember(_ context.Context, in *__.GetUserMemberReq) (*__.GetUserMemberResp, error) {
	var user model.User
	err := user.GetUserMember(config.DB, int(in.UserId))
	if err != nil {
		return nil, err
	}
	return &__.GetUserMemberResp{
		Username:         user.Username,
		MemberStatus:     int64(user.MemberStatus),
		MemberExpireTime: int64(user.MemberExpireTime),
	}, nil
}
